package product_logic

import (
	"errors"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
	"wx-uniapp-go/third_party/oss"
)

// GetProductDetail 获取商品详情
func (l *ProductLogic) GetProductDetail(req *dto.ProductDetailReq) (*dto.ProductDetailResp, error) {
	// 查询商品信息
	var product models.Product
	exist, err := models.Get(l.Ctx, &product, "id = ? AND status = ?", req.Id, models.ProductStatusOnSale)
	if err != nil {
		return nil, err
	}
	if !exist {
		return nil, errors.New("商品不存在")
	}

	// 转换规格信息
	specInfo := make([]*dto.SpecInfo, len(product.SpecInfo))
	for i, spec := range product.SpecInfo {
		specInfo[i] = &dto.SpecInfo{
			SpecName:  spec.SpecName,
			SpecId:    spec.SpecId,
			SpecPrice: 0, // 这里需要根据业务逻辑设置具体价格
		}
	}

	// 处理图片路径
	detailImages := make([]string, len(product.DetailImages))
	for i, img := range product.DetailImages {
		detailImages[i] = oss.Cli.JoinPath(img)
	}

	bannerImages := make([]string, len(product.BannerImages))
	for i, img := range product.BannerImages {
		bannerImages[i] = oss.Cli.JoinPath(img)
	}

	modelList, err := models.ProductModelFindByIDs(l.Ctx, product.Models)
	if err != nil {
		return nil, err
	}

	tagList, err := models.ProductTagNameByIDs(l.Ctx, product.Tags)
	if err != nil {
		return nil, err
	}
	// 转换响应
	resp := &dto.ProductDetailResp{
		Id:            product.Id,
		Title:         product.Title,
		Cover:         oss.Cli.JoinPath(product.Cover),
		DetailImages:  detailImages,
		BannerImages:  bannerImages,
		Price:         product.Price,
		OriginPrice:   product.OriginPrice,
		Stock:         product.Stock,
		SalesVolume:   product.SalesVolume,
		Tags:          tagList,
		Models:        make([]*dto.Models, 0),
		Categorys:     product.Categorys,
		Unit:          product.Unit,
		Weight:        product.Weight,
		SpecInfo:      specInfo,
		SkuList:       product.SkuList,
		DeliveryTypes: product.DeliveryTypes,
		Description:   product.Description,
		Notice:        product.Notice,
		IsRecommend:   product.IsRecommend,
		IsNew:         product.IsNew,
		IsHot:         product.IsHot,
		MinBuyNum:     product.MinBuyNum,
		MaxBuyNum:     product.MaxBuyNum,
	}
	for _, model := range modelList {
		resp.Models = append(resp.Models, &dto.Models{
			Name:  model.Name,
			Color: model.Color,
		})
	}
	return resp, nil
}
